package com.ls.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.server.domain.DictCategory;
import com.ls.server.domain.DictItem;
import com.ls.server.dto.DictItemDTO;
import com.ls.server.dto.DictQueryDTO;
import com.ls.server.mapper.DictCategoryMapper;
import com.ls.server.mapper.DictItemMapper;
import com.ls.server.service.DictItemService;
import com.ls.server.vo.DictItemVO;
import com.ls.server.vo.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 字典小类服务实现类
 */
@Service
public class DictItemServiceImpl extends ServiceImpl<DictItemMapper, DictItem> implements DictItemService {

    private final DictCategoryMapper dictCategoryMapper;

    public DictItemServiceImpl(DictCategoryMapper dictCategoryMapper) {
        this.dictCategoryMapper = dictCategoryMapper;
    }

    @Override
    public PageResult<DictItemVO> page(DictQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<DictItem> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(queryDTO.getName())) {
            wrapper.like(DictItem::getName, queryDTO.getName());
        }
        if (StringUtils.hasText(queryDTO.getCode())) {
            wrapper.like(DictItem::getCode, queryDTO.getCode());
        }
        if (queryDTO.getCategoryId() != null) {
            wrapper.eq(DictItem::getCategoryId, queryDTO.getCategoryId());
        }
        wrapper.orderByAsc(DictItem::getSort);

        // 分页查询
        IPage<DictItem> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());
        page = baseMapper.selectPage(page, wrapper);

        // 获取所有相关的字典大类ID
        List<Long> categoryIds = page.getRecords().stream()
                .map(DictItem::getCategoryId)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询字典大类
        Map<Long, DictCategory> categoryMap = dictCategoryMapper.selectBatchIds(categoryIds)
                .stream()
                .collect(Collectors.toMap(DictCategory::getId, Function.identity(), (k1, k2) -> k1));

        // 转换为VO
        List<DictItemVO> records = page.getRecords().stream()
                .map(item -> convertToVO(item, categoryMap.get(item.getCategoryId())))
                .collect(Collectors.toList());

        // 返回分页结果
        return new PageResult<DictItemVO>(records, page.getTotal(), queryDTO.getPage(), queryDTO.getSize());
    }

    @Override
    public List<DictItemVO> listByCategoryId(Long categoryId) {
        // 查询指定字典大类下的所有字典项
        List<DictItem> list = baseMapper.selectList(
                new LambdaQueryWrapper<DictItem>()
                        .eq(DictItem::getCategoryId, categoryId)
                        .orderByAsc(DictItem::getSort)
        );

        // 查询字典大类
        DictCategory category = dictCategoryMapper.selectById(categoryId);

        // 转换为VO
        return list.stream()
                .map(item -> convertToVO(item, category))
                .collect(Collectors.toList());
    }

    @Override
    public DictItemVO getById(Long id) {
        DictItem item = baseMapper.selectById(id);
        if (item == null) {
            return null;
        }

        DictCategory category = dictCategoryMapper.selectById(item.getCategoryId());
        return convertToVO(item, category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(DictItemDTO dto) {
        // 验证字典大类是否存在
        DictCategory category = dictCategoryMapper.selectById(dto.getCategoryId());
        if (category == null) {
            throw new RuntimeException("字典大类不存在");
        }

        DictItem item = new DictItem();
        BeanUtils.copyProperties(dto, item);
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        item.setCreateTime(now);
        item.setUpdateTime(now);
        item.setCreator("admin"); // 实际应从当前登录用户获取
        item.setUpdater("admin"); // 实际应从当前登录用户获取
        
        return baseMapper.insert(item) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(DictItemDTO dto) {
        DictItem item = baseMapper.selectById(dto.getId());
        if (item == null) {
            return false;
        }
        
        // 如果修改了字典大类，则验证字典大类是否存在
        if (!item.getCategoryId().equals(dto.getCategoryId())) {
            DictCategory category = dictCategoryMapper.selectById(dto.getCategoryId());
            if (category == null) {
                throw new RuntimeException("字典大类不存在");
            }
        }
        
        BeanUtils.copyProperties(dto, item);
        item.setUpdateTime(LocalDateTime.now());
        item.setUpdater("admin"); // 实际应从当前登录用户获取
        
        return baseMapper.updateById(item) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    /**
     * 将实体转换为VO
     * @param item 实体
     * @param category 字典大类
     * @return VO
     */
    private DictItemVO convertToVO(DictItem item, DictCategory category) {
        if (item == null) {
            return null;
        }
        DictItemVO vo = new DictItemVO();
        BeanUtils.copyProperties(item, vo);
        
        if (category != null) {
            vo.setCategoryName(category.getName());
        }
        
        return vo;
    }
} 